package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

//   @RequiresRoles("ADMIN")    //权限表达式  可以配置多个,默认是&&，要求同时拥有多个权限才能访问该方法 改成or相当于||
    @RequiresPermissions(value = {"role:list","角色列表"},logical = Logical.OR)
//    @RequiredPermission(name="角色列表",expression="role:list")
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo){
        model.addAttribute("pageInfo", roleService.query(qo));
        return "role/list"; // 找视图 /WEB-INF/views/role/list.jsp
    }


    @RequiresPermissions(value = {"role:xxxx","角色xxx"},logical = Logical.OR)
    @RequestMapping("/list2")
    public String list2(Model model, QueryObject qo){
        model.addAttribute("pageInfo", roleService.query(qo));
        return "role/list"; // 找视图 /WEB-INF/views/role/list.jsp
    }

//    @RequiredPermission(name="角色删除",expression="role:delete")
    @RequestMapping("/delete")
    public String delete(Long id){
        if (id != null) {
            roleService.delete(id);
        }
        return "redirect:/role/list.do"; // 让重新发一次请求
    }

    // 去新增或去修改
    @RequestMapping("/input")
    public String input(Long id, Model model){
        //查询所有的权限
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions",permissions);

        if (id != null) { // 表示去修改
            Role role = roleService.get(id);
            model.addAttribute("role", role);
        }
        return "role/input"; // 让重新发一次请求
    }

    // 新增或修改
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids){
        if(role.getId()  == null){ // 新增
            roleService.save(role,ids);
        }else {
            roleService.update(role,ids); // 修改
        }
        return "redirect:/role/list.do"; // 让重新发一次请求
    }


}
